package com.smashcrush.server.context;


public class SecurityContext {

	/** Thread-local sessionHandler session. */
	private static final ThreadLocal<SecurityContext> sessionHandler = new ThreadLocal<SecurityContext>();

	String userId;

	public SecurityContext() {
	}

	/**
	 * Get the CommonSession for the calling thread.
	 * 
	 * @return CommonSession for calling thread
	 */
	public static SecurityContext get() {
		final SecurityContext commonSession = sessionHandler.get();
		// if (commonSession == null) {
		// throw new RuntimeException(
		// "there is no SecurityContext attached to current thread "
		// + Thread.currentThread().getName());
		// }
		return commonSession;
	}

	/**
	 * Create/Retrieve the session and call this to set it for the duration of
	 * the request. Make sure to call unset() after the request is finished.
	 * <p>
	 * Sets CommonSession for calling thread.
	 * 
	 * @param CommonSession
	 *            The CommonSession
	 */
	public static void set(final SecurityContext commonSession) {
		if (commonSession == null) {
			throw new IllegalArgumentException(
					"Argument CommonSession can not be null");
		}
		sessionHandler.set(commonSession);
	}

	/**
	 * Clears the CommonSession for calling thread.
	 * 
	 */
	public static void unset() {
		sessionHandler.set(null);
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public boolean isAuthenticated() {
		return userId != null;
	}

}
